package com.marktotop.controller;

import com.marktotop.entity.Page;
import com.marktotop.entity.Student;
import com.marktotop.service.StudentManager;
import jdk.nashorn.internal.ir.CallNode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 学生控制器
 * @author WXLD
 * @data 2021/5/10 - 10:23
 */
public class StudentController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @return DAO方法对象
     */
    public StudentManager getService(){
        String path = "src/main/resources/student.xml";

        //创建学生管理类
        StudentManager sm = new StudentManager(path);
        return sm;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String methodName=req.getParameter("methodName");
        int method=Integer.parseInt(methodName);
        try {
            switch(method)
            {
                case 0:
                    insert(req,resp);
                case 1:
                    difpage(req,resp);
                    break;
                case 2:
                    delete(req,resp);
                    break;
                case 3:
                    update(req,resp);
                    break;
                case 4:
                    update(req,resp);
                    break;
                case 5:
                    dispatch(req,resp);
                    break;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    };


    /**
     * 添加学生方法
     * @param request
     * @param response
     * @throws Exception
     */
    public void insert(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StudentManager service = getService();
        Student newStd = new Student()
                .setId(request.getParameter("id"))
                .setName(request.getParameter("name"))
                .setSex(request.getParameter("sex"))
                .setAge(request.getParameter("age"))
                .setGradeName(request.getParameter("gradeName"))
                .setMajor(request.getParameter("major"))
                .setContact(request.getParameter("contact"))
                .setAddress(request.getParameter("address"));
        service.addStudent(newStd);
    }


    /**
     * 查询全部学生信息
     * @return
     * @throws Exception
     */
    public Student select(String id) throws Exception {
        StudentManager service = getService();
        Student byId = service.findById(id);
        return byId;
    }


    /**
     * 条件查询跳转
     * @param request
     * @param response
     * @throws Exception
     */
    public void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String id5=request.getParameter("id");

        if(select(id5) == null){
            // 跳转至 未找到结果页面
            request.getRequestDispatcher("selectnothing.jsp").forward(request, response);
        }
        else{
            // 跳转至 结果页面
            request.setAttribute("result", select(id5));
            request.getRequestDispatcher("idnameselect.jsp").forward(request, response);
        }
    }


    /**
     * 学生信息删除方法
     * @param request
     * @param response
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        StudentManager service = getService();
        String id2 = request.getParameter("id");
        boolean result = service.removeById(id2);
        if (result == true){
            request.getRequestDispatcher("delete.jsp").forward(request, response);
        }
    }


    /**
     * 更新学生信息
     * @param request
     * @param response
     * @throws Exception
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StudentManager service = getService();
        Student newStd = new Student()
                .setId(request.getParameter("id"))
                .setName(request.getParameter("name"))
                .setSex(request.getParameter("sex"))
                .setAge(request.getParameter("age"))
                .setGradeName(request.getParameter("gradeName"))
                .setMajor(request.getParameter("major"))
                .setContact(request.getParameter("contact"))
                .setAddress(request.getParameter("address"));
        boolean result = service.updateStudent(newStd);
        if (result == true){
            request.getRequestDispatcher("update.jsp").forward(request, response);
        }
    }


    /**
     * 设置分页相关参数方法
     * @param request
     * @param response
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Page setpage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String crd=request.getParameter("currentRecord");

        StudentManager service = getService();
        List<Student> students = service.findAll();

        Page pager=new Page();
        pager.setTotalRecord(students.size());
        pager.setTotalPage(students.size(),pager.getPageSize());

        if(crd!=null)
        {
            int currentRecord=Integer.parseInt(crd);
            pager.setCurrentRecord(currentRecord);
            pager.setCurrentPage(currentRecord,pager.getPageSize());
        }
        return pager;
    }


    /**
     * 获得分页显示的子集
     * @param request
     * @param response
     * @throws Exception
     */
    public void difpage(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StudentManager service = getService();
        List<Student> students = service.findAll();

        Page pager=new Page();
        pager=setpage(request,response);
        List<Student> subResult=null;
        int currentRecord=pager.getCurrentRecord();
        if(currentRecord==0){
            if(pager.getTotalRecord()<8){
                subResult=(List<Student>) students.subList(0,pager.getTotalRecord());
            }
            else{
                subResult=(List<Student>) students.subList(0,pager.getPageSize());
            }
        }
        else if(pager.getCurrentRecord()+pager.getPageSize()<students.size())
        {
            subResult=(List<Student>) students.subList(pager.getCurrentRecord(),pager.getCurrentRecord()+pager.getPageSize());
        }
        else
        {
            subResult=(List<Student>) students.subList(pager.getCurrentRecord(),students.size());
        }
        request.setAttribute("pager", pager);
        request.setAttribute("subResult", subResult);
        request.getRequestDispatcher("layout.jsp").forward(request, response);
    }
}
